import React, { useState } from 'react';

// 新增：解析消息内容，识别图片URL并渲染图片
function renderMessageContent(content) {
    // 匹配 Markdown 图片语法 ![xxx](url) 或直接的 http(s) 图片链接（如 .webp）
    const imgRegex = /!\[.*?\]\((https?:\/\/[^\s)]+)\)|((https?:\/\/[^\s)]+\.(?:webp|png|jpg|jpeg|gif)))/g;
    const parts = [];
    let lastIndex = 0;
    let match;
    let key = 0;

    while ((match = imgRegex.exec(content)) !== null) {
        // 文本部分
        if (match.index > lastIndex) {
            parts.push(<span key={key++}>{content.slice(lastIndex, match.index)}</span>);
        }
        // 图片部分
        const url = match[1] || match[2];
        if (url) {
            parts.push(<img key={key++} src={url} alt="图片" style={{maxWidth: '220px', borderRadius: '8px', margin: '8px 0', display: 'block'}} />);
        }
        lastIndex = imgRegex.lastIndex;
    }
    // 剩余文本
    if (lastIndex < content.length) {
        parts.push(<span key={key++}>{content.slice(lastIndex)}</span>);
    }
    return parts;
}

function ChatWindow({ conversationId }) {
    const [messages, setMessages] = useState([
        { id: 1, content: 'Hello! How can I assist you today?', sender: 'Qwen3-235B-A22B' },
    ]);
    const [inputValue, setInputValue] = useState('');
    const [loading, setLoading] = useState(false); // 新增
    const sendMessage = async () => {
        if (inputValue.trim() === '') return;

        // 先加入用户消息
        const userMsg = { id: messages.length + 1, content: inputValue, sender: 'user' };
        setMessages(prev => [...prev, userMsg]);
        const currentInput = inputValue;
        setInputValue('');
        setLoading(true); // 开始loading
        try {
            const res = await fetch('http://127.0.0.1:8000/root', {
                method: 'POST',
                headers: {
                    'accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ query: currentInput })
            });
            const data = await res.json();
            if (data && data.message) {
                setMessages(prev => [
                    ...prev,
                    { id: prev.length + 1, content: data.message, sender: 'Qwen3-235B-A22B' }
                ]);
            }
        } catch (e) {
            setMessages(prev => [
                ...prev,
                { id: prev.length + 1, content: '接口请求失败，请稍后重试。', sender: 'Qwen3-235B-A22B' }
            ]);
        }
        setLoading(false); // 结束loading
    };

    return (
        <div className="chat-window">
            <div className="message-list">
                {messages.map(message => (
                    <div key={message.id} className={`message ${message.sender}`}>
                        {renderMessageContent(message.content)}
                    </div>
                ))}
                 {loading && (
                    <div className="message Qwen3-235B-A22B">
                        <span className="loading-dots">
                            <span>。</span><span>。</span><span>。</span>
                        </span>
                    </div>
                )}
            </div>
            <div className="input-area">
                <input
                    type="text"
                    value={inputValue}
                    onChange={(e) => setInputValue(e.target.value)}
                    onKeyDown={e => { if (e.key === 'Enter') sendMessage(); }}
                    placeholder="有什么我能帮您的吗？"
                />
                <button onClick={sendMessage}>发送</button>
            </div>
        </div>
    );
}

export default ChatWindow;